import React, { Component } from 'react'
import {withRouter} from 'react-router-dom'
import { Form, Input, Button, Checkbox, message, Select, Spin } from 'antd'
import {
  UserOutlined,
  LockOutlined,
  PhoneOutlined,
  MailOutlined,
  TeamOutlined,
} from '@ant-design/icons';
import Request from '@utils/request'

import {userUrl} from '@config/url'
import {REGISTER_SUCCESS, REGISTER_USERNAME_EXIST} from '@config/code'

import style from './index.module.css'

const { Option } = Select

const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 8,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
    },
  },
};

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
};

class RegisterForm extends Component {

  state = {isLoading: false}

  onFinish = async (val) => {
    
    // console.log('val', val)
    const postData = {
      username: val.username.trim(),
      password: val.password.trim(),
      phone:    val.phone ? val.phone.trim() : val.phone,
      email:    val.email ? val.email.trim() : val.email,
      usertype: val.usertype,
      gender:   val.gender,
    }
    console.log('postData', postData)

    this.setState({isLoading:true})
    setTimeout(() => this.setState({isLoading: false}), 3000)
    
    const data = await Request(userUrl.register, postData)
    // console.log(data)
    switch (data.code) {
      case REGISTER_SUCCESS:
        message.success('注册成功，即将转到登录页面.....')
        const {history, to} = this.props
        setTimeout(() => history.push(to), 1000)
        break
      case REGISTER_USERNAME_EXIST:
        message.error('注册失败，用户名已存在')
        break
      default:
        message.error('注册失败，ERROR:', data.msg)
        break
    }
    
    this.setState({isLoading:false})
  }

  render() {
    // console.log("render", this)
    return (
      <Form
        {...formItemLayout}
        name="register"
        className={style["register-form"]}
        initialValues={{ usertype: 0}}
        onFinish={this.onFinish}
      >
        <Form.Item
          name="username"
          label="Username"
          rules={[
            { required: true, message: 'Please input your Username!' },
            { whitespace: true, message: 'input is blank' }
          ]}
        >
          <Input prefix={<UserOutlined />}/>
        </Form.Item>

        <Form.Item
          name="password"
          label="Password"
          rules={[{ required: true, message: 'Please input your Password!' }]}
        >
          <Input.Password prefix={<LockOutlined />} />
        </Form.Item>

        <Form.Item
          name="confirm"
          label="Confirm Password"
          dependencies={['password']}
          rules={[
            { required: true, message: 'Please input your Password!'},
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }

                return Promise.reject(new Error('The two passwords that you entered do not match!'));
              },
            }),
          ]}
        >
          <Input.Password prefix={<LockOutlined />} />
        </Form.Item>

        <Form.Item 
          name="phone" 
          label="Phone"
          rules={[{pattern:'^ *1\\d{10} *$', message:'phone number error'}]}
        >
          <Input prefix={<PhoneOutlined />} />
        </Form.Item>

        <Form.Item name="email" label="E-mail" rules={[{type:'email', message:'email type error'}]}>
          <Input prefix={<MailOutlined />} />
        </Form.Item>

        <Form.Item
          name="usertype"
          label="User Type"
          rules={[
            {required:true, message:'Please select group user or normal user!'}
          ]}
        >
          <Select prefix={<TeamOutlined/>} placeholder="select your user type">
            <Option value={0}>normal</Option>
            <Option value={1}>group</Option>
          </Select>
        </Form.Item>

        <Form.Item name="gender" label="Gender"  style={{marginBottom:10}} rules={[{type:'number',}]}>
          <Select>
            <Option value={0}>female</Option>
            <Option value={1}>male</Option>
          </Select>
        </Form.Item>

        <Form.Item 
          name="agreement"
          valuePropName="checked"
          rules={[
            {
              validator: (_, value) => 
                value ? Promise.resolve() : Promise.reject(new Error('Should accept agreement')),
            },
          ]}
          style={{marginBottom:10}}
          {...tailFormItemLayout}
        >
          <Checkbox className={style["agreement"]}>
            I have read the <a href="/tmp">agreement</a>
          </Checkbox>
        </Form.Item>

        <Form.Item {...tailFormItemLayout}>
          <Spin tip="Loading ...." spinning={this.state.isLoading}>
            <Button
              type="primary"
              htmlType="submit"
              className={style["submit"]}
            >
              Register
            </Button>
          </Spin>
          <a className={style["to-login"]} href="/user/login">Has account ?</a>
        </Form.Item>
      </Form>
    )
  }
}

export default withRouter(RegisterForm)
//withRouter可以加工一般组件，让一般组件具备路由组件所特有的API
//withRouter的返回值是一个新组件